# 导入所需模块
import requests
import tkinter as tk
from tkinter import font
import json
import hashlib
import random
import functools
# 随机给出请求头中的 user-agent
# 模拟多个 user-agent，随机选取 list 中的一个
user_agents = [
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
    "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
    "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
    "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
    "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
    "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
]
# 完成随机选取 user-agnet，实现 反 反爬 操作
request_headers = {
    'user-agent': random.choice(user_agents),
    'Referer': 'http://mifan.61.com/',
    'Origin': 'http://mifan.61.com',
    'Host': 'mifan.61.com'
}

def create_window():
    # 创建主窗口
    window = tk.Tk()
    window.title("签到信息")
    window.geometry("300x180")
    window.iconbitmap("favicon.ico")
    return window

def clear_win():
    for ele in window.winfo_children():
        ele.destroy()

def submit_info(uid, password):
    # 获取切换账号、密码，更新界面、获取登录信息
    data = login(uid, password)
    try:
        request_headers['Authorization'] = data['token']  # 获取token
    except KeyError:
        # 账号密码错误
        try:
            show_msg(data['data'])
            return
        except KeyError:#被封号了，返回的内容是个联系管理员网页
            return
    except:
        return # 登录请求都失败了
    data = daily_sign()  # 签到
    show_msg(data['data'])  # 显示签到信息

def show_login(event=None):
    clear_win()
    # 创建一个新的Frame容器，并设置为登录界面的Frame
    login_frame = tk.Frame(window)
    login_frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
    custom_font = font.Font(family="Helvetica", size=18, weight="bold")

    # 创建账号文本框和标签，保存引用为实例变量
    uid_label = tk.Label(login_frame, text="账号:", font=custom_font)
    uid_label.grid(row=0, column=0)
    uid_entry = tk.Entry(login_frame)
    uid_entry.grid(row=0, column=1)


    # 创建密码文本框和标签，保存引用为实例变量
    password_label = tk.Label(login_frame, text="密码:", font=custom_font)
    password_label.grid(row=1, column=0)
    password_entry = tk.Entry(login_frame, show="*")
    password_entry.grid(row=1, column=1)

    submit_button = None
    def subbtn(uid, pwd, event=None):
        # 点击"提交后，重新获取签到信息"
        uid = uid.get()
        pwd = pwd.get()
        submit_info(uid, pwd)

    # 创建提交按钮
    submit_button = tk.Button(window, text="提交", command=functools.partial(subbtn, (uid_entry), (password_entry)))
    submit_button.bind('<Return>', functools.partial(subbtn, (uid_entry), (password_entry)))
    submit_button.place(relx=0.95, rely=0.95, anchor=tk.SE)

def login(uid, password):
    # 发起请求，参数为用户名、密码
    # 创建MD5对象
    md5 = hashlib.md5()

    # 更新MD5对象的输入（字节）
    md5.update(password.encode('utf-8'))

    # 获取加密后的结果
    encrypted_data = md5.hexdigest()

    # print("加密后的数据:", encrypted_data)
    data = {
        'gid':'689',# 摩尔庄园
        'uid':uid,
        'password':encrypted_data,
        'tad':'',
        'encrypt':'true'
    }
    url = 'https://mifan.61.com/api/v1/login'
    try:
        res = requests.post(url= url,data= data, headers= request_headers, timeout= 5)
        # print('res.text:', res.text)
    except:
        show_msg('请检查网络连接(｡•́︿•̀｡)')
        return

    try:
        data = json.loads(res.text)
    except json.decoder.JSONDecodeError:
        show_msg('被封号了..切换网络试试(｡•́︿•̀｡)',fontsize= 12)
        return

    return data

def show_msg(text,fontsize = 18):
    clear_win()
    custom_font = font.Font(family="Helvetica", size=fontsize, weight="bold")

    # 创建签到信息界面的Frame
    frame = tk.Frame(window)
    frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

    # 创建标签并设置文本内容
    label = tk.Label(frame, text=text, anchor=tk.CENTER, font=custom_font)
    label.pack()

    # 创建切换账号按钮
    switch_button = tk.Button(window, text="切换账号", command=show_login)# 展示切换账号页面
    switch_button.bind('<Return>', show_login)
    switch_button.place(relx=0.95, rely=0.95, anchor=tk.SE)

def daily_sign():
    # 使用登录后获取的token进行签到
    url = 'https://mifan.61.com/api/v1/event/dailysign/'
    res = requests.post(url=url,  headers= request_headers)
    data = json.loads(res.text)
    return data

window = create_window()  # 创建窗口
def main():

    show_msg('签到中...')
    uid = '936363254'
    password = 'XXX'

    submit_info(uid, password)
    window.resizable(False, False)
    window.mainloop()

# 声明主程序入口
if __name__ == '__main__':
    try:
        main()
    except requests.exceptions.ConnectionError:
        show_msg('请检查网络连接(｡•́︿•̀｡)')

